package com.lyl.syt.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.lyl.syt.common.exception.YyghException;
import com.lyl.syt.common.result.ResultCodeEnum;
import com.lyl.syt.constant.OssConstant;
import com.lyl.syt.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
public class FileServiceImpl implements FileService {
    @Override
    public String uploadFile(MultipartFile file) {
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = OssConstant.ENDPOINT;
        String accessKeyId = OssConstant.ACCESS_KEY_ID;
        String accessKeySecret = OssConstant.ACCESS_KEY_SECRET;
        String bucketName = OssConstant.BUCKET_NAME;

        String fileName = file.getOriginalFilename();
        //生成随机的唯一值（使用uuid，添加到文件名称里面）
        String uuid = UUID.randomUUID().toString().replaceAll("-","");
        fileName = uuid + fileName;
        //按照当前日期，创建文件夹 2021/02/01.jpg
        String timeURL = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        fileName =  timeURL + "/" + fileName;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            InputStream inputStream = file.getInputStream();
            // 创建PutObject请求。
            ossClient.putObject(bucketName, fileName, inputStream);

            return "https://" + bucketName + "." + endpoint + "/" + fileName;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (IOException e) {
            throw new YyghException(ResultCodeEnum.OSS_UPLOAD_ERROR);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return "";
    }
}
